package com.xli.dto.validation.sql;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Pattern;

public class SqlInjectionValidator implements ConstraintValidator<SqlInjection, String> {

    // 定义正则表达式来检测不安全的字符或SQL关键字
    private static final Pattern SQL_INJECTION_PATTERN = Pattern.compile("(['\"])|(--|#|;|\\b(select|insert|update|delete|drop|union|exec|count|information_schema|--|sleep)\\b)", Pattern.CASE_INSENSITIVE);

    // 定义正则表达式来检测不合规的空格（多个连续空格）
    private static final Pattern INVALID_SPACE_PATTERN = Pattern.compile("\\s+");

    @Override
    public void initialize(SqlInjection constraintAnnotation) {
        // 初始化方法，不需要做任何事
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.isEmpty()) {
            return true;
        }
        return !isSqlInjection(value) && !hasInvalidSpaces(value);
    }

    // SQL 注入检测
    private boolean isSqlInjection(String input) {
        return SQL_INJECTION_PATTERN.matcher(input).find();
    }

    // 空格检查：检测是否包含多个连续空格
    private boolean hasInvalidSpaces(String input) {
        return INVALID_SPACE_PATTERN.matcher(input).find();
    }
}
